package com.enjoy.jvm.hotspot.src.share.tools;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;

public class DataTranslate {

    private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', '6', '7', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    public static int byteToUnsignedShort(byte[] bytes){
        int high = bytes[0];
        int low = bytes[1];
        return (high << 8 & 0xFF00) | (low & 0xFF);
    }

    /**
     * byte[]转int
     * @param bytes 需要转换成int的数组
     * @return int值
     */
    public static int byteArrayToInt(byte[] bytes) {
        int value=0;

        for(int i = 0; i < 4; i++) {
            int shift= (3-i) * 8;
            value +=(bytes[i] & 0xFF) << shift;
        }

        return value;
    }

    public static float byteToFloat(byte[] b) {
        int l;

        l = b[3];
        l &= 0xff;
        l |= (int) ((long) b[2] << 8);
        l &= 0xffff;
        l |= (int) ((long) b[1] << 16);
        l &= 0xffffff;
        l |= (int) ((long) b[0] << 24);

        return Float.intBitsToFloat(l);
    }
    public static long bytesToLong(byte[] arr) {
        ByteBuffer buffer = ByteBuffer.wrap(arr, 0, 8);

        return buffer.getLong();
    }

    public static double bytesToDouble(byte[] arr, boolean littleEndian) {
        ByteBuffer buffer = ByteBuffer.wrap(arr,0,8);

        if (littleEndian) {
            buffer.order(ByteOrder.LITTLE_ENDIAN);
        }

        return buffer.getDouble();
    }



}
